<?php
/*
+------------------------------------------------------------------------------+
| Copyright (c) 2008, Draftrack Team                                           |
| All rights reserved.                                                         |
|                                                                              |
| Redistribution and use in source and binary forms, with or without           |
| modification, are permitted provided that the following conditions are met:  |
|     * Redistributions of source code must retain the above copyright         |
|       notice, this list of conditions and the following disclaimer.          |
|     * Redistributions in binary form must reproduce the above copyright      |
|       notice, this list of conditions and the following disclaimer in the    |
|       documentation and/or other materials provided with the distribution.   |
|     * Neither the name of the <organization> nor the                         |
|       names of its contributors may be used to endorse or promote products   |
|       derived from this software without specific prior written permission.  |
|                                                                              |
| THIS SOFTWARE IS PROVIDED BY draftrack team ''AS IS'' AND ANY                |
| EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED    |
| WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE       |
| DISCLAIMED. IN NO EVENT SHALL draftrack team BE LIABLE FOR ANY               |
| DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES   |
| (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
| LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND  |
| ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
| (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS|
| SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                 |
+------------------------------------------------------------------------------+
*/
/**
 * @category   Myzen
 * @package    Myzen_Log
 */
 
class Myzen_Log_Executiontime
{
	/**
     * Singleton instance
     *
     * @var Zend_ExecutionTime
     */
    protected static $_instance = null;
	
	/**
     * time when the timer has been launched (done automatically at instenciation)
     * @var float
     */
    protected static $_startTime = 0;

	/**
     * Holds the enable value for the logger
     * @var boolean
     */
    protected $_logEnabled = false;

	/**
     * Holds the PHP stream to log to.
     * @var null|stream
     */
    protected $_stream = null;
    
    
    protected $_moduleName = '';
    protected $_controllerName = '';
    protected $_actionName = '';
    
    /**
     * Singleton pattern implementation makes "new" unavailable
     *
     * @return void
     */
    protected function __construct() {}

    /**
     * Singleton pattern implementation makes "clone" unavailable
     *
     * @return void
     */
    protected function __clone() {}
    
    
    /**
     * Returns an instance of Zend_Auth
     *
     * Singleton pattern implementation
     *
     * @return Zend_ExecutionTime
     */
    public static function getInstance() {
        if (null === self::$_instance) {
            self::$_instance = new self();
            self::$_startTime = microtime(true);
        }

        return self::$_instance;
    }
    
    
    /**
     * Set the configuration for the logging of the execution time
     * valid parameters 
     *	- enable: boolean for the logging
     *	- log_stream : where should the long queries be logged
     *  - minimum_runtime: int time in second under which the query is not logged
     * @param void
     * @return void
     */    
    public function setConfig($config) {
        
        if ($config instanceof Zend_Config) {
            $config = $config->toArray();
        }
        
        if (!is_array($config)) {
            throw new Myzen_Log_Exception('executiontime: config parameters must be in an array or a Zend_Config object');
        }
        
        if(isset($config['enable'])) {
        	$this->_logEnabled = (bool) $config['enable'];		
        }
        
        //We check that the stream is available
         	$streamOrUrl = $config['log_stream'];
	        if (is_resource($streamOrUrl)) {
    	        if (get_resource_type($streamOrUrl) != 'stream') {
        	        $this->_logEnabled = false;
        	        throw new Myzen_Log_Exception('executiontime: Resource is not a stream');
        	    }
        	    $this->_stream = $streamOrUrl;
        	} else {
            	if (! $this->_stream = @fopen($streamOrUrl, 'a', false)) {
					$this->_logEnabled = false;
            	    $msg = "executiontime: \"$streamOrUrl\" cannot be opened";
            	    throw new Myzen_Log_Exception($msg);
            	}
        	}
        
    }

    /**
     * save the time in seconds since the classe instanciation
     * @param void
     * @return int time in milliseconds to render the page
     */
    public function saveTime() {
    	try {
	    	$log = Zend_Registry::get('dt_log');
    	} catch(Zend_Exception $e) {}
    	
    	$executionTime = microtime(true) - self::$_startTime;
    	$executionTimeMs = round($executionTime * 1000);
    	if($this->_logEnabled) {
    	    
    	    if (is_resource($this->_stream)) {
    	    	
    	    	$request = Zend_Controller_Front::getInstance()->getRequest();
		    	$page = $request->getModuleName().':'.$request->getControllerName().':'.$request->getActionName();
    	    	$consumerKey = @$request->getParam('draftrack_consumerKey');
				
    	    	$string = time().':'.$consumerKey.':'.$page.':'.$executionTimeMs;
	        	if (false === @fwrite($this->_stream, $string."\n")) {
					if(isset($log)) $log->log('executiontime: could not write in the stream', Zend_Log::ERR);
        		}	
	        }
            fclose($this->_stream);
        }

		if(isset($log)) $log->log('page took '.$executionTimeMs.'ms to render', Zend_Log::INFO); 

    	return $executionTimeMs;
    }
}

?>